package com.backend.api.controller;

import com.util.CommonResult;
import com.common.model.User;
import com.backend.api.security.entity.SelfAdminEntity;
import com.backend.api.security.jwt.JwtTokenUtil;
import com.backend.api.security.service.SelfUserDetailsService;
import com.backend.api.util.UserUtil;
import io.swagger.annotations.ApiOperation;
import net.minidev.json.JSONArray;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 用于验证 jwt 返回客户端 jwt（json web token）
 */
@RestController
@CrossOrigin
public class JwtAuthenticationController {

    private AuthenticationManager authenticationManager;

    private JwtTokenUtil jwtTokenUtil;

    private SelfUserDetailsService userService;

    public JwtAuthenticationController(AuthenticationManager authenticationManager, JwtTokenUtil jwtTokenUtil, SelfUserDetailsService userService) {
        this.authenticationManager = authenticationManager;
        this.jwtTokenUtil = jwtTokenUtil;
        this.userService = userService;
    }

    /**
     * 获取 客户端来的 username password 使用秘钥加密成 json web token
     */
    @ApiOperation("获取JWT秘钥")
    @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
    public CommonResult<?> createAuthenticationToken(@RequestBody User userRequest) throws Exception {

        authenticate(userRequest.getUsername(), userRequest.getPassword());

        final UserDetails userDetails = userService.loadUserByUsername(userRequest.getUsername());

        final String token = jwtTokenUtil.generateToken(userDetails);

        Map<String, String> data = new HashMap<>();
        data.put("token", token);

        return CommonResult.success(data);
    }

    @ApiOperation("获取用户信息")
    @RequestMapping(value = "/userInfo", method = RequestMethod.GET)
    public CommonResult<?> getUserInfoByToken() {

        SelfAdminEntity selfAdminEntity = UserUtil.getLoginAdmin();

        Map<String, String> data = new HashMap<>();

        if (selfAdminEntity != null) {

            data.put("name", selfAdminEntity.getUsername());
            data.put("avatar", selfAdminEntity.getAvatar());
            //组装权限并返回
            Collection<GrantedAuthority> authorities = selfAdminEntity.getAuthorities();

            List<String> roles = new ArrayList<>();
            for (GrantedAuthority rule : authorities) {
                roles.add(rule.getAuthority());
            }
            data.put("roles", JSONArray.toJSONString(roles));

            return CommonResult.success(data);
        } else {
            return CommonResult.success("用户未登录");
        }
    }

    /**
     * 获取 客户端来的 username password 使用秘钥加密成 json web token
     */
    private void authenticate(String username, String password) throws Exception {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (DisabledException e) {
            throw new Exception("USER_DISABLED", e);
        } catch (BadCredentialsException e) {
            throw new Exception("INVALID_CREDENTIALS", e);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }
}